/*******************************************************************************
 * Copyright (c) 2011 squid.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     squid - initial API and implementation
 ******************************************************************************/
package com.google.code.cubeirc.queue;

import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

import lombok.Getter;
import lombok.Synchronized;


public final class MessageQueue {


	@Getter
	private static final ConcurrentLinkedQueue<MessageQueueListener> listeners = new ConcurrentLinkedQueue<MessageQueueListener>();

	@Getter
	private static final ConcurrentLinkedQueue<MessageQueueEvent> events = new ConcurrentLinkedQueue<MessageQueueEvent>();

	@Synchronized
	public final static void addListener(final MessageQueueListener listener)
	{
		getListeners().add(listener);
	}

	@Synchronized
	public final static void removeListener(final MessageQueueListener listener)
	{
		Iterator<MessageQueueListener> it =  getListeners().iterator();
		while(it.hasNext())
		{
			MessageQueueListener li = it.next();
			if (li.equals(listener))
			{
				listeners.remove(li);
			}
		}
	}

	@Synchronized
	public static final void addQueue(final MessageQueueEnum msgtype,final Object data)
	{
		addQueue(new MessageQueueEvent(msgtype,data));
	}

	@Synchronized
	public static final void addQueue(final MessageQueueEvent event)
	{		
		getEvents().add(event);
       //DebuggerQueue.addDebug(event, Level.TRACE, "Adding message to queue: Type: %s", event.getData().getClass().getName());	


		if (getListeners().size() > 0)
		{
			while (!getEvents().isEmpty())
				processQueue(getEvents().poll());
		}

	}

	@Synchronized
	public static final void processQueue(final MessageQueueEvent event)
	{
		Iterator<MessageQueueListener> it = getListeners().iterator();
		while (it.hasNext())
		{
			it.next().actionPerformed(event);
		}
	}

}
